from datetime import datetime
import re

import pymysql
import time

#数据库参数
DB_CONFIG={
"host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "root",
    "database": "apptest"
}


# 日志级别映射
LOG_LEVELS = {'D', 'I', 'W', 'E', 'F'}  # 调试/信息/警告/错误/致命/

data_log=[]

def init_db():
    #连接数据库
    con = pymysql.connect(**DB_CONFIG)
    return con

def read_log():
    #初始化数据存放列表
    data_log.clear()
    # 初始化日志级别计数器
    counters = {level: 0 for level in LOG_LEVELS}
    #打开日志文件
    with open(r"baijia.log",encoding='utf-8') as file:
        #按行读取
        for line in file:
            line = line.strip()
            #先分离时间戳
            parts = re.split(r'\s+', line,maxsplit=2)  # 按任意空白符（空格、制表符等）分割
            if len(parts) >= 3:
                #单独处理剩下的部分，分为四段
                detail=parts[2].split(maxsplit=3)
                # 合并前两个字段（parts[0]和parts[1]）
                dt_str=f"{parts[0]} {parts[1]}"
                #将时间戳转成日期
                current_year = datetime.now().year
                full_str = f"{current_year}-{dt_str}"
                dt = datetime.strptime(full_str, "%Y-%m-%d %H:%M:%S.%f")
                #计数
                if detail[2] in LOG_LEVELS:
                    counters[detail[2]] += 1
                #合并数据
                if detail[2] == 'E' or detail[2] == 'F':
                    merged = [dt] + [detail[2]]+[counters[detail[2]]]+[detail[3]]
                else:
                    merged= [dt] + [detail[2]]+[counters[detail[2]]]+['']
                #print(merged)
                data_log.append(merged)
            else:
                print("日志格式错误")
        #打印信息
        print(f"错误出现了{counters['E']}次，调试信息出现{counters['D']}次，警告出现了{counters['W']}次，普通消息出现{counters['I']}次")
    return data_log

def upload_db(param):
    #连接数据库
    con = init_db()
    cursor = con.cursor()
    #清空数据表
    sql='TRUNCATE TABLE log_info'
    cursor.execute(sql)
    #批量插入
    sql='INSERT INTO log_info (create_time,log_level,log_count,log_detail) VALUES(%s,%s,%s,%s)'
    cursor.executemany(sql,param)
    #提交事务
    con.commit()
    #清理资源
    cursor.close()
    con.close()

if __name__ == "__main__":
    #读取日志文件
    data=read_log()
    #上传至数据库
    upload_db(data)